package cn.efunbox.afw.data.redis.serialize;

import org.springframework.core.convert.converter.Converter;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Created by Dreampie on 16/9/1.
 */
public class JdkSerializationRedisPrefixSerializer extends JdkSerializationRedisSerializer {
  public static StringRedisSerializer stringSerializer = new StringRedisSerializer();
  private Converter<Object, byte[]> serializer;
  private Converter<byte[], Object> deserializer;

  public JdkSerializationRedisPrefixSerializer(String prefix) {
    byte[] prefixBytes = stringSerializer.serialize(prefix);
    this.serializer = new SerializingPrefixConverter(prefixBytes);
    this.deserializer = new DeserializingPrefixConverter(prefixBytes);
  }

  public Object deserialize(byte[] bytes) {
    if (bytes == null || bytes.length == 0) {
      return null;
    } else {
      try {
        return this.deserializer.convert(bytes);
      } catch (Exception var3) {
        try {
          return stringSerializer.deserialize(bytes);
        } catch (Exception var4) {
          throw new SerializationException("Cannot deserialize", var3);
        }
      }
    }
  }

  public byte[] serialize(Object object) {
    if (object == null) {
      return new byte[0];
    } else {
      try {
        if (object instanceof String) {
          return (byte[]) stringSerializer.serialize((String) object);
        } else {
          return (byte[]) this.serializer.convert(object);
        }
      } catch (Exception var3) {
        throw new SerializationException("Cannot serialize", var3);
      }
    }
  }

}
